package com.itheima.mp.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.mp.Service.IUserService;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.dto.UserFormDTO;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "用户管理接口")
@RequestMapping("/users")
@RestController
@RequiredArgsConstructor
public class UserController {

    private final IUserService userService;

    @ApiOperation("新增用户接口")
    @PostMapping
    public void  saveUser(@RequestBody UserFormDTO userFormDTO){
        //1.把DTO拷贝到PO
        User user = BeanUtil.copyProperties(userFormDTO, User.class);
        //2.新增
        userService.save(user);
    }

    @ApiOperation("删除用户接口")
    @DeleteMapping("{id}")
    public void  deleteUserById(@PathVariable("id") Long id){
        userService.removeById(id);
    }

    @ApiOperation("根据id查询用户接口")
    @GetMapping("/{id}")
    public UserVO getById(@PathVariable("id") Long id){
        //1.查询用户
        User user = userService.getById(id);
        //2.PO转换成VO
        return BeanUtil.copyProperties(user, UserVO.class);
    }

    @ApiOperation("根据id查询用户及收货地址的接口")
    @GetMapping("/getUserAndAddress/{id}")
    public UserVO getUserAndAddress(@PathVariable("id") Long id){
       return userService.queryUserAndAddressById(id);
    }

    @ApiOperation("根据id批量查询用户接口")
    @GetMapping("/ids")
    public List<UserVO> getById(@RequestParam("ids") List<Long> ids){
        //1.查询用户
        List<User> users = userService.listByIds(ids);
        //2.PO转换成VO
        return BeanUtil.copyToList(users, UserVO.class);
    }

    @ApiOperation("根据id批量查询用户及收货地址的接口")
    @GetMapping("/getUserAndAddressByIds/ids")
    public List<UserVO> getUserAndAddressByIds(@RequestParam("ids") List<Long> ids){
        List<UserVO> userVOS = userService.queryUserAndAddressByIds(ids);
        return userVOS;
    }


    @ApiOperation("扣减用户余额接口")
    @PutMapping("/{id}/deduction/{money}")
    public void deductMoneyById(@PathVariable("id") Long id, @PathVariable("money") Integer money){
        userService.deductMoneyById(id,money);
    }

    @ApiOperation("根据复杂条件查询用户接口")
    @PutMapping("/list")
    public List<UserVO> queryUsers(UserQuery query){
        List<User> users = userService.queryUsers(query.getName(), query.getStatus(), query.getMinBalance(), query.getMaxBalance());
        return BeanUtil.copyToList(users, UserVO.class);
    }

    @ApiOperation("根据复杂条件分页查询用户接口")
    @GetMapping("/page")
    public PageDTO<UserVO> queryUsersPage(UserQuery query){
        return userService.queryUsersPage(query);
    }
}
